<?php

include './Http.class.php';

//get post data, May be due to the different environments
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];//$_POST。

// file_put_contents('./data.txt', $postStr);
// die();

//extract post data
if (!empty($postStr)){
        /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
           the best way is to check the validity of xml by yourself */
        libxml_disable_entity_loader(true);
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $keyword = trim($postObj->Content);
        $time = time();
                    
        if(!empty( $keyword ))
        {

            $url = "https://api.heweather.com/x3/citylist?search=allchina&key=f827a6c7b72a4cce92be9cad1cd134a0";
            $jsonData = Http::get($url);
            $jsonArr = json_decode($jsonData, true);
            $arr = $jsonArr['city_info'];
            foreach ($arr as $k => $v) {
                if($v['city'] == $keyword)
                {
                    $url = "https://api.heweather.com/x3/weather?cityid=".$v['id']."&key=f827a6c7b72a4cce92be9cad1cd134a0";
                    $resData = Http::get($url);
                    $res = json_decode($resData, true);
                    $data = $res['HeWeather data service 3.0'][0]['daily_forecast'];
                    
                    $str = "<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[news]]></MsgType>
                            <ArticleCount>7</ArticleCount>
                            <Articles>";

                    foreach ($data as $key => $val) {
                        $str .= "<item>
                        <Title><![CDATA[".$keyword." ".$val['date'].' '.$val['cond']['txt_d']." 转 ".$val['cond']['txt_n'].' 最高温度 '.$val['tmp']['max'].' 最低温度 '.$val['tmp']['min'] ."]]></Title> 
                        <Description><![CDATA[description1]]></Description>
                        <PicUrl><![CDATA[http://files.heweather.com/cond_icon/".$val['cond']['code_d'].".png]]></PicUrl>
                        <Url><![CDATA[http://www.baidu.com]]></Url>
                        </item>";
                    }

                    $str .= "</Articles>
                        </xml>";
                }
            }
            $resultStr = sprintf($str, $fromUsername, $toUsername, $time);
            echo $resultStr;

        }else{
            echo "Input something...";
        }

}else {
    echo "";
    exit;
}